package com.easyidea.its.domain.repository.department.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.easyidea.its.domain.model.system.Department;
import com.easyidea.its.domain.repository.base.impl.BaseRepositoryImpl;
import com.easyidea.its.domain.repository.department.DepartmentRepository;

public class DepartmentRepositoryImpl extends BaseRepositoryImpl<Department> implements
		DepartmentRepository {

	public int getDeparmentsCount(Department dept) {
		Criteria criteria =  getDepartmentsCriteria(dept);
		criteria.setProjection(Projections.count("id"));
		return (Integer)criteria.uniqueResult();
	}

	public List<Department> getDepartments(Department dept, int startAtIndex,
			int pageSize) {
		Criteria criteria =  getDepartmentsCriteria(dept);
		if(startAtIndex > 0) {
			criteria.setFirstResult(startAtIndex);
		}
		if (pageSize > 0) {
			criteria.setMaxResults(pageSize);
		}
		return criteria.list();
	}
    private Criteria getDepartmentsCriteria(Department dept) {
    	Criteria criteria = createUndeleteCriteria();
    	if(dept.getDepartmentName() != null && !dept.getDepartmentName().equals("")) {
    		criteria.add(Restrictions.ilike("departmentName", dept.getDepartmentName(), MatchMode.START));	
    	}
    	return criteria;
    }
	public boolean hasSameDeptName(String deptName, Integer id) {
		Criteria criteria = createUndeleteCriteria();
		criteria.add(Restrictions.eq("departmentName", deptName));
		criteria.add(Restrictions.ne("id", id));
		List<Department> ds = criteria.list();
		if (ds != null && ds.size() > 0) {
			return true;
		}
		return false;
	}

}
